<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/04/11 20:58:15 $)
// $RCSfile: functions_parserrulesui.php,v $ : $Revision: 1.4 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Insert a new Parser Rule
*/
function insertParserRule($title, $sortorder, $ruletype, $matchtype, $stopprocessing, $criteria, $actions)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($criteria) || !_is_array($actions))
	{
		return false;
	}

	// First Insert the Parser Rule
	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."parserrules` (`title`, `dateline`, `sortorder`, `ruletype`, `matchtype`, `stopprocessing`) VALUES ('". $dbCore->escape($title) ."', '". DATENOW ."', '". intval($sortorder) ."', '". intval($ruletype) ."', '". intval($matchtype) ."', '". intval($stopprocessing) ."');");
	$parserruleid = $dbCore->lastInsertId();
	if (!$parserruleid)
	{
		return false;
	}

	processCriteriaAndActions($parserruleid, $criteria, $actions);

	return $parserruleid;
}

/**
* Update existing Parser Rule
*/
function updateParserRule($parserruleid, $title, $sortorder, $ruletype, $matchtype, $stopprocessing, $criteria, $actions)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($criteria) || !_is_array($actions))
	{
		return false;
	}

	$dbCore->query("UPDATE `". TABLE_PREFIX ."parserrules` SET `title` = '". $dbCore->escape($title) ."', `dateline` = '". DATENOW ."', `sortorder` = '". intval($sortorder) ."', `ruletype` = '". intval($ruletype) ."', `matchtype` = '". intval($matchtype) ."', `stopprocessing` = '". intval($stopprocessing) ."' WHERE `parserruleid` = '". intval($parserruleid) ."';");

	deleteCriteriaAndActions(array($parserruleid));
	processCriteriaAndActions($parserruleid, $criteria, $actions);

	return true;
}

/**
* Deletes the given parser rules
*/
function deleteParserRules($parserruleidlist)
{
	global $dbCore;

	if (!_is_array($parserruleidlist))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."parserrules` WHERE `parserruleid` IN (". buildIN($parserruleidlist) .");");

	deleteCriteriaAndActions($parserruleidlist);

	return true;
}

/**
* Deletes the Criteria and Actions under the given parser rule
*/
function deleteCriteriaAndActions($parserruleidlist)
{
	global $dbCore;

	if (!_is_array($parserruleidlist))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."rulecriteria` WHERE `parserruleid` IN (". buildIN($parserruleidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ruleactions` WHERE `parserruleid` IN (". buildIN($parserruleidlist) .");");

	return true;
}

/**
* Processes the Critera And Actions
*/
function processCriteriaAndActions($parserruleid, &$criteria, &$actions)
{
	global $dbCore;

	// Insert the Criterias
	$_criteriasql = array();
	foreach ($criteria as $key=>$val)
	{
		$_criteriasql[] = "('". intval($parserruleid) ."', '". $dbCore->escape($val["name"]) ."', '". intval($val["ruleop"]) ."', '". $dbCore->escape($val["rulematch"]) ."')";
	}
	if (count($_criteriasql))
	{
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."rulecriteria` (`parserruleid`, `name`, `ruleop`, `rulematch`) VALUES ".implode(",", $_criteriasql).";");
	}

	// Now we insert the actions
	$_actionsql = array();
	foreach ($actions as $key=>$val)
	{
		$_actionsql[] = "('". intval($parserruleid) ."', '". $dbCore->escape($val["name"]) ."', '". intval($val["typeid"]) ."', '". $dbCore->escape($val["typedata"]) ."', '". $dbCore->escape($val["typechar"]) ."')";
	}

	if (count($_actionsql))
	{
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."ruleactions` (`parserruleid`, `name`, `typeid`, `typedata`, `typechar`) VALUES ". implode(",", $_actionsql).";");
	}

	return true;
}

/**
* Convert Array to JS to Render the Criteria
*/
function criteriaArrayToForm($_criteria)
{
	foreach ($_criteria as $key=>$val)
	{
		$jscode .= 'newRuleCriteria(\''. addslashes($val["name"]) .'\', \''. intval($val["ruleop"]) .'\', \''. addslashes($val["rulematch"]) .'\');'.SWIFT_CRLF;
	}

	return $jscode;
}

/**
* Convert Criteria Form Data to Array
*/
function criteriaFormToArray()
{
	$_criteria = array();
	$index = 0;

	if (!_is_array($_POST["rulecriteria"]))
	{
		return $_criteria;
	}

	foreach ($_POST["rulecriteria"] as $key=>$val)
	{
		$_criteria[$index]["name"] = $val[0];
		$_criteria[$index]["ruleop"] = $val[1];
		$_criteria[$index]["rulematch"] = $val[2];
		$index++;
	}

	return $_criteria;
}

/**
* Processes the Rule Actions and converts them into form variables
*/
function processRuleToFormActions($actions)
{
	if (!_is_array($actions))
	{
		return false;
	}

	foreach ($actions as $key=>$val)
	{
		if ($val["name"] == PARSERACTION_REPLY)
		{
			$_POST["replycontents"] = $val["typedata"];
		} else if ($val["name"] == PARSERACTION_FORWARD) {
			$_POST["forwardemail"] = $val["typechar"];
		} else if ($val["name"] == PARSERACTION_IGNORE || $val["name"] == PARSERACTION_NOAUTORESPONDER || $val["name"] == PARSERACTION_NOALERTRULES || $val["name"] == PARSERACTION_NOTICKET) {
			$_POST[$val["name"]] = "1";
		} else if ($val["name"] == PARSERACTION_DEPARTMENT) {
			$_POST["departmentid"] = $val["typeid"];
		} else if ($val["name"] == PARSERACTION_STATUS) {
			$_POST["ticketstatusid"] = $val["typeid"];
		} else if ($val["name"] == PARSERACTION_PRIORITY) {
			$_POST["priorityid"] = $val["typeid"];
		} else if ($val["name"] == PARSERACTION_OWNER) {
			$_POST["staffid"] = $val["typeid"];
		} else if ($val["name"] == PARSERACTION_FLAGTICKET) {
			$_POST["flagtype"] = $val["typeid"];
		} else if ($val["name"] == PARSERACTION_SLAPLAN) {
			$_POST["slaplanid"] = $val["typeid"];
		} else if ($val["name"] == PARSERACTION_ADDNOTE) {
			$_POST["notes"] = $val["typedata"];
		}
	}
}

/**
* Processes the form and returns the unified Action Array
*/
function processFormRuleActions()
{
	global $_SWIFT;

	$_actions = array();
	$index = 0;

	// ======= PRE PARSE RULES =======
	if ($_POST["ruletype"] == RULE_PREPARSE && trim($_POST["replycontents"]) != "")
	{
		$_actions[$index]["name"] = PARSERACTION_REPLY;
		$_actions[$index]["typedata"] = $_POST["replycontents"];
		$index++;
	}
	if ($_POST["ruletype"] == RULE_PREPARSE && trim($_POST["forwardemail"]) != "")
	{
		$_actions[$index]["name"] = PARSERACTION_FORWARD;
		$_actions[$index]["typechar"] = $_POST["forwardemail"];
		$index++;
	}
	if ($_POST["ruletype"] == RULE_PREPARSE && $_POST[PARSERACTION_IGNORE] == "1")
	{
		$_actions[$index]["name"] = PARSERACTION_IGNORE;
		$index++;
	}
	if ($_POST["ruletype"] == RULE_PREPARSE && $_POST[PARSERACTION_NOAUTORESPONDER] == "1")
	{
		$_actions[$index]["name"] = PARSERACTION_NOAUTORESPONDER;
		$index++;
	}
	if ($_POST["ruletype"] == RULE_PREPARSE && $_POST[PARSERACTION_NOALERTRULES] == "1")
	{
		$_actions[$index]["name"] = PARSERACTION_NOALERTRULES;
		$index++;
	}
	if ($_POST["ruletype"] == RULE_PREPARSE && $_POST[PARSERACTION_NOTICKET] == "1")
	{
		$_actions[$index]["name"] = PARSERACTION_NOTICKET;
		$index++;
	}

	// ======= POST PARSE RULES =======
	if ($_POST["ruletype"] == RULE_POSTPARSE && !empty($_POST["departmentid"]))
	{
		$_actions[$index]["name"] = PARSERACTION_DEPARTMENT;
		$_actions[$index]["typeid"] = $_POST["departmentid"];
		$index++;
	}
	if ($_POST["ruletype"] == RULE_POSTPARSE && !empty($_POST["ticketstatusid"]))
	{
		$_actions[$index]["name"] = PARSERACTION_STATUS;
		$_actions[$index]["typeid"] = $_POST["ticketstatusid"];
		$index++;
	}
	if ($_POST["ruletype"] == RULE_POSTPARSE && !empty($_POST["priorityid"]))
	{
		$_actions[$index]["name"] = PARSERACTION_PRIORITY;
		$_actions[$index]["typeid"] = $_POST["priorityid"];
		$index++;
	}
	if ($_POST["ruletype"] == RULE_POSTPARSE && !empty($_POST["staffid"]))
	{
		$_actions[$index]["name"] = PARSERACTION_OWNER;
		$_actions[$index]["typeid"] = $_POST["staffid"];
		$index++;
	}
	if ($_POST["ruletype"] == RULE_POSTPARSE && !empty($_POST["flagtype"]))
	{
		$_actions[$index]["name"] = PARSERACTION_FLAGTICKET;
		$_actions[$index]["typeid"] = $_POST["flagtype"];
		$index++;
	}
	if ($_POST["ruletype"] == RULE_POSTPARSE && !empty($_POST["slaplanid"]))
	{
		$_actions[$index]["name"] = PARSERACTION_SLAPLAN;
		$_actions[$index]["typeid"] = $_POST["slaplanid"];
		$index++;
	}
	if ($_POST["ruletype"] == RULE_POSTPARSE && trim($_POST["notes"]) != "")
	{
		$_actions[$index]["name"] = PARSERACTION_ADDNOTE;
		$_actions[$index]["typedata"] = $_POST["notes"];
		$index++;
	}

	return $_actions;
}

/**
* Renders the Parser Rule Form
*/
function renderRuleForm($type, $ruletype)
{
	global $dbCore, $_SWIFT;

	printFormStart();
	printMainTableHeader(iif($type==INSERT, $_SWIFT["language"]["insertrule"], $_SWIFT["language"]["editrule"]));

	printTextRow("title", $_SWIFT["language"]["ptitle"], $_SWIFT["language"]["desc_ptitle"], "text", $_POST["title"]);
	printYesNoRow("stopprocessing", $_SWIFT["language"]["pstop"], $_SWIFT["language"]["desc_pstop"]);

	// Sort Order
	if ($type == INSERT)
	{
		$_sortorder = $dbCore->queryFetch("SELECT `sortorder` FROM `". TABLE_PREFIX ."parserrules` ORDER BY `sortorder` DESC LIMIT 1;");
		if (empty($_sortorder["sortorder"]))
		{
			$_POST["sortorder"] = 1;
		} else {
			$_POST["sortorder"] = $_sortorder["sortorder"]+1;
		}
	}
	printNumberRow("sortorder", $_SWIFT["language"]["sortorder"], $_SWIFT["language"]["desc_sortorder"], $_POST["sortorder"]);

	printDescRow($_SWIFT["language"]["criteria"]);

	echo '<tr class="'. getRowBG() .'">
	<td align="left" colspan="2"><span class="smalltext"><div id="ruleparent"></div></span></td></tr>';

	if ($type == INSERT || ($type == EDIT && $_POST["matchtype"] == RULE_MATCHALL))
	{
		$matchall = true;
	}

	echo '<tr class="'. getRowBG() .'">
	<td align="left" colspan="2"><span class="smalltext"><a href="javascript:newRuleCriteria(\'sendername\', \''. OP_CONTAINS .'\', \'\');"><img src="'. $_SWIFT["themepath"] .'icon_add.gif" border="0" align="absmiddle" />&nbsp;'. $_SWIFT["language"]["newcriteria"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label for="ruleall"><input type="radio" name="ruleoptions" value="all" id="ruleall"'. iif($matchall==true," checked") .'>'. $_SWIFT["language"]["smatchall"] .'</label>&nbsp;<label for="ruleany"><input type="radio" name="ruleoptions" value="any" id="ruleany"'. iif($matchall!=true," checked") .'>'. $_SWIFT["language"]["smatchany"] .'</label></span></td></tr>';

	printDescRow($_SWIFT["language"]["iruletype"].'&nbsp;<label for="preparse"><input type="radio" id="preparse" name="ruletype" onClick="if (this.checked) {switchRuleType(1);}" style="PADDING: 0px; MARGIN: 0px;" value="1"'. iif($ruletype == RULE_PREPARSE, " checked") .'>&nbsp;'.$_SWIFT["language"]["ipreparse"].'</label>&nbsp;&nbsp;&nbsp;<label for="postparse"><input type="radio" onClick="if (this.checked) {switchRuleType(2);}" id="postparse" name="ruletype" style="PADDING: 0px; MARGIN: 0px;" value="2"'. iif($ruletype == RULE_POSTPARSE, " checked") .'>&nbsp;'.$_SWIFT["language"]["ipostparse"].'</label>');


	// ======= PRE PARSE ACTIONS =======
	printTextareaRow("replycontents", $_SWIFT["language"]["preply"], $_SWIFT["language"]["desc_preply"], $_POST["replycontents"], "60", "8", false, "pre4", "DISPLAY: none;");
	printTextRow("forwardemail", $_SWIFT["language"]["pcforward"], $_SWIFT["language"]["desc_pcforward"], "text", $_POST["forwardemail"], "30", "0", "pre5", "DISPLAY: none;");
	printYesNoRow(PARSERACTION_IGNORE, $_SWIFT["language"]["paignore"], $_SWIFT["language"]["desc_paignore"], false, "", "pre1", "DISPLAY: none;");
	printYesNoRow(PARSERACTION_NOAUTORESPONDER, $_SWIFT["language"]["panoautoresp"], $_SWIFT["language"]["desc_panoautoresp"], false, "", "pre2", "DISPLAY: none;");
	printYesNoRow(PARSERACTION_NOALERTRULES, $_SWIFT["language"]["panoalerts"], $_SWIFT["language"]["desc_panoalerts"], false, "", "pre3", "DISPLAY: none;");
	printYesNoRow(PARSERACTION_NOTICKET, $_SWIFT["language"]["panoticket"], $_SWIFT["language"]["desc_panoticket"], false, "", "pre6", "DISPLAY: none;");

	// ======= POST PARSE ACTIONS =======
	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["pnochange"];
	$options[0]["value"] = "0";
	$options[0]["selected"] = true;
	$index = 1;
	foreach ($_SWIFT["departmentcache"] as $key=>$val)
	{
		if ($val["departmentmodule"] == MODULE_TICKETS)
		{
			$options[$index]["title"] = $val["title"];
			$options[$index]["value"] = $val["departmentid"];
			$index++;
		}
	}
	printSelectRow("departmentid", $_SWIFT["language"]["pcdepartment"], $_SWIFT["language"]["desc_pcdepartment"], $options, "", "DISPLAY: none;");

	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["pnochange"];
	$options[0]["value"] = "0";
	$options[0]["selected"] = true;
	$index = 1;
	foreach ($_SWIFT["staffcache"] as $key=>$val)
	{
		$options[$index]["title"] = $val["fullname"];
		$options[$index]["value"] = $val["staffid"];
		$index++;
	}
	printSelectRow("staffid", $_SWIFT["language"]["pcstaff"], $_SWIFT["language"]["desc_pcstaff"], $options, "", "DISPLAY: none;");

	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["pnochange"];
	$options[0]["value"] = "0";
	$options[0]["selected"] = true;
	$index = 1;
	foreach ($_SWIFT["statuscache"] as $key=>$val)
	{
		$options[$index]["title"] = $val["title"];
		$options[$index]["value"] = $val["ticketstatusid"];
		$index++;
	}
	printSelectRow("ticketstatusid", $_SWIFT["language"]["pcstatus"], $_SWIFT["language"]["desc_pcstatus"], $options, "", "DISPLAY: none;");

	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["pnochange"];
	$options[0]["value"] = "0";
	$options[0]["selected"] = true;
	$index = 1;
	foreach ($_SWIFT["prioritycache"] as $key=>$val)
	{
		$options[$index]["title"] = $val["title"];
		$options[$index]["value"] = $val["priorityid"];
		$index++;
	}
	printSelectRow("priorityid", $_SWIFT["language"]["pcpriority"], $_SWIFT["language"]["desc_pcpriority"], $options, "", "DISPLAY: none;");

	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["pnochange"];
	$options[0]["value"] = "0";
	$options[0]["selected"] = true;
	$index = 1;
	foreach ($_SWIFT["slaplancache"] as $key=>$val)
	{
		$options[$index]["title"] = $val["title"];
		$options[$index]["value"] = $val["slaplanid"];
		$index++;
	}
	printSelectRow("slaplanid", $_SWIFT["language"]["pcslaplan"], $_SWIFT["language"]["desc_pcslaplan"], $options, "", "DISPLAY: none;");

	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["pnochange"];
	$options[0]["value"] = "0";
	$options[0]["selected"] = true;
	$options[1]["title"] = $_SWIFT["language"]["purpleflag"];
	$options[1]["value"] = FLAG_PURPLE;
	$options[2]["title"] = $_SWIFT["language"]["redflag"];
	$options[2]["value"] = FLAG_RED;
	$options[3]["title"] = $_SWIFT["language"]["orangeflag"];
	$options[3]["value"] = FLAG_ORANGE;
	$options[4]["title"] = $_SWIFT["language"]["yellowflag"];
	$options[4]["value"] = FLAG_YELLOW;
	$options[5]["title"] = $_SWIFT["language"]["blueflag"];
	$options[5]["value"] = FLAG_BLUE;
	$options[6]["title"] = $_SWIFT["language"]["greenflag"];
	$options[6]["value"] = FLAG_GREEN;
	printSelectRow("flagtype", $_SWIFT["language"]["pcflag"], $_SWIFT["language"]["desc_pcflag"], $options, "", "DISPLAY: none;");

	printTextareaRow("notes", $_SWIFT["language"]["paddnotes"], $_SWIFT["language"]["desc_paddnotes"], $_POST["notes"], "50", "3", false, "post7", "DISPLAY: none;");

	printSubmitRow(iif($type == INSERT, $_SWIFT["language"]["insert"], $_SWIFT["language"]["update"]));

	printMainTableFooter();

	addHiddenField("_m", "parser");
	addHiddenField("_a", iif($type==INSERT, "insertparserrule", "editparserrule"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("parserruleid", $_POST["parserruleid"]);
	}
	printFormEnd();
}
?>